package signGrammar.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import signGrammar.IShape;
import signGrammar.util.CShapePrinter;

public class CViewShapePane extends JPanel{
	private static final long serialVersionUID = 1L;
	
	private boolean wasDraggedFlag = false;
	private Point headPoint = new Point( getWidth() / 2, getHeight() / 2 );
	
	private final class CMouseDragListener extends MouseMotionAdapter {
		@Override public void mouseDragged( MouseEvent e ) {
			int onmask = MouseEvent.BUTTON1_DOWN_MASK;
			if( (e.getModifiersEx() & onmask) == onmask ){
				wasDraggedFlag = true;
				
				int dx = e.getX() - headPoint.x;
				int dy = e.getY() - headPoint.y;
				
				headPoint = new Point( headPoint.x + dx, headPoint.y + dy );
				
				repaint();
			}
		}
	}

	private IShape shape = null;
	private String shapeName = null;
		
	public CViewShapePane(IShape shape, String shapeName) {
		init(shape, shapeName);
	}
	public CViewShapePane( IShape shape ) {
		init(shape, null);
	}
	public CViewShapePane() {
		init(null, null);
	}
	
	private void init(IShape shape, String name){		
		this.shape = shape;
		this.shapeName = name;
		setBackground( Color.white );
		setBorder( BorderFactory.createEtchedBorder() );
		setPreferredSize( new Dimension(20,20) );
		addMouseMotionListener(new CMouseDragListener());
	}

	public CViewShapePane setShape( IShape shape ){
		this.shape = shape;
		repaint();
		return this;
	}
	public String getShapeName() {
		return shapeName;
	}
	public CViewShapePane setShapeName(String shapeName) {
		this.shapeName = shapeName;
		return this;
	}
	
	private Point getCenterPoint(){
		return new Point( getWidth() / 2, getHeight() / 2 );
	}
	
	private Point getHeadPoint(){
		if( !wasDraggedFlag )
			return getCenterPoint();
		return headPoint;
	}
	
	@Override
	public void paint(Graphics graphics){
		super.paint(graphics);
		
		assert graphics != null : "CViewShapePane.paint: graphics object can't be null";
		assert shape    != null : "CViewShapePane.paint: shape object can't be null";
		
		if( shape != null && graphics != null ){
			CShapePrinter.printWithHeadsAndTails(graphics, shape.cloneForHead( getHeadPoint() ));
			if( shapeName != null )
				CShapePrinter.printShapeName(graphics, shapeName);
		}
	}	
}
